package com.heliang.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.heliang.common.FileLog;
import com.hl.component.LoadingView;


public class AsyncImageLoaderAddLoading {
	private static final String TAG="AsyncImageLoader";
		
//	private HashMap<String, SoftReference<Drawable>> imageCache;
	private HashMap<String, List<LoadingView>> ivListHashMap;
	private HashMap<String, LoadingView> urlCache;
	private BlockingQueue queue ;   
	private ThreadPoolExecutor executor ;
	  
	     public AsyncImageLoaderAddLoading() {
//	    	 imageCache = new HashMap<String, SoftReference<Drawable>>();
	    	 urlCache = new HashMap<String, LoadingView>();
	    	 ivListHashMap = new HashMap<String, List<LoadingView>>();
	    	 // 线程池：最大50条，每次执行：1条，空闲线程结束的超时时间：180秒
	    	 queue = new LinkedBlockingQueue();
	    	 executor = new ThreadPoolExecutor(3, 50, 180, TimeUnit.SECONDS, queue);
	     }
	  
	     /**
	      * 
	      * @param imagePath
	      * @param imageUrl
	      * @param liv
	      * @param imageCallback
	      * @return
	      */
	     public LoadingView loadDrawable(final String imagePath, final String imageUrl,LoadingView liv, final ImageCallback imageCallback) {
//	         if (imageCache.containsKey(imageUrl)) {
//	             SoftReference<Drawable> softReference = imageCache.get(imageUrl);
//	             Drawable drawable = softReference.get();
//	             if (drawable != null) {
//	                 return drawable;
//	             }
//	         }
//	    	 ImageView iv = null;
	    	 try {
	    		 if (urlCache.containsKey(imageUrl)) {//有重复的
//		    		 iv = urlCache.get(imageUrl);
		    		 List<LoadingView> livListTemp = ivListHashMap.get(imageUrl);
		    		 if (livListTemp != null) {
						livListTemp.add(liv);
		    		 }
		    		 
		    		 Log.v("test", "contain " + liv.getId() + "--" + imageUrl);
//		    		 if (iv != null) {
//		    			 changeIvCallback.changeIv(iv);
//		    		 }
		    		 
		    		 return liv;
		    	 }else {//第一个IV
		    		 
		    		 List<LoadingView> livList = new ArrayList<LoadingView>();
		    		 livList.add(liv);
		    		 urlCache.put(imageUrl, liv);
		    		 ivListHashMap.put(imageUrl, livList);
		    	 }
		    	 
//		    	 final ImageView ivTemp = iv;
		         final Handler handler = new Handler() {
		             public void handleMessage(Message message) {
		            	 List<LoadingView> livList = ivListHashMap.get(imageUrl);
		            	 
		            	 urlCache.remove(imageUrl);
		            	 ivListHashMap.remove(imageUrl);
		                 imageCallback.imageLoaded(imagePath,(Drawable) message.obj, livList);
		             }
		         };
		         
			    File file = new File(imagePath);// 保存文件    
		        if(!file.exists()&& !file.isDirectory()){  
		        	putExecutor(imageUrl,imagePath,liv,handler);
		        }else{  
		        	 Drawable drawable = loadImageFromLocal(imagePath);
		        	 if (drawable == null) {
		        		 putExecutor(imageUrl,imagePath,liv,handler);
					}else {
						Message message = handler.obtainMessage(0, drawable);
		                handler.sendMessage(message);	
					}
	                 
//	                 urlCache.remove(imageUrl);
		           
		        } 
			} catch (Exception e) {
				// TODO: handle exception
				FileLog.log("AsyncImageLoader " + e.getMessage());
			}
	    	 

	         return liv;
	     }
	     
	     /**
	      * 把下载图片加入线程池u
	      */
	     private void putExecutor(final String imageUrl,final String imagePath,LoadingView liv,final Handler handler){
//	    	 urlCache.put(imageUrl, liv);
		    	Log.v("test", liv.getId() + "--" + imageUrl);
	        	// 用线程池来做下载图片的任务
		         executor.execute(new Runnable() {
		             @Override
		             public void run() {
		                 Drawable drawable = loadImageFromUrl(imagePath, imageUrl);
		                 Message message = handler.obtainMessage(0, drawable);
		                 handler.sendMessage(message);
//		                 urlCache.remove(imageUrl);
		             }
		         });
	     }
	     
	     
	    /* *//**
	      * 
	      * @param urlPath
	      * @return
	      * @throws IOException
	      *//*
	     public static byte[] readByte(String urlPath) throws IOException{

	    	 URL url = new URL(urlPath) ;

	    	 InputStream inStream ;

	    	 HttpURLConnection conn = (HttpURLConnection)url.openConnection() ;

	    	 conn.setConnectTimeout(6*1000);

	    	 inStream = conn.getInputStream() ;

	    	 byte[] buffer = new byte[1024] ;

	    	 --生成一个字节数组输出流对象--

	    	 ByteArrayOutputStream outStream = new ByteArrayOutputStream() ;

	    	 int len = -1 ;

	    	 while((len = inStream.read(buffer)) != -1){

	    		 outStream.write(buffer, 0, len);

	    	 }

	    	 inStream.close() ;

	    	 outStream.close() ;

	    	 --返回字节数组流--

	    	 return outStream.toByteArray() ;

	     }
    	 *//**
    	  * 将字节数组转换为ImageView可调用的Bitmap对象 
    	  * @param bytes
    	  * @param opts
    	  * @return
    	  *//*

    	 public static Bitmap getPicFormByte(byte[] bytes ){

    	 if ( bytes != null){

    		 return BitmapFactory.decodeByteArray(bytes, 0,bytes.length);

    	 }
    	 return null;

    	 }*/
	  
	    /*// 网络图片先下载到本地cache目录保存，以imagUrl的图片文件名保存。如果有同名文件在cache目录就从本地加载
		public static Drawable loadImageFromUrl(String imagePath, String imageUrl) {
			Drawable drawable = null;  
			
	        if(imagePath == null && imageUrl == null )  
	            return null;  
	  
	        String pathTmp = imagePath.substring(0, imagePath.lastIndexOf("/"));
	        String fileName = imagePath.substring(imagePath.lastIndexOf("/") + 1);
	        File directory = new File(pathTmp);
	        
	        if (!directory.exists()) {
	        	directory.mkdirs();
			}
	        
	        File file = new File(imagePath);// 保存文件  
	          
	        if(!file.exists()&& !file.isDirectory())  
	        {  

		        File fileTmp = new File(Constants.SDCARD_PATH + Constants.PATH_TEMP + fileName);//临时文件 
		        File directoryTmp = new File(Constants.SDCARD_PATH + Constants.PATH_TEMP);
		        
//		        if (fileTmp.exists()) {
//					if (condition) {
//						
//					}
//				}
		        if (!directoryTmp.exists()) {
		        	directoryTmp.mkdirs();
				}
		        
	        	FileOutputStream fos;  
	            InputStream is;  
	            try {  
	                // 可以在这里通过文件名来判断，是否本地有此图片  
	                  
	                fos=new   FileOutputStream( fileTmp );  
	                is = new URL(imageUrl).openStream();  
	                int   data = is.read();   
	                while(data!=-1){   
	                        fos.write(data);   
	                        data=is.read();;   
	                }   
	                fos.close();  
	                is.close();  
//	              drawable = Drawable.createFromStream(  
//	                      new URL(imageUrl).openStream(), file.toString() ); // (InputStream) new URL(imageUrl).getContent();  
	                drawable = Drawable.createFromPath(fileTmp.toString());  
	                FileIOUtil.moveFile(fileTmp.getAbsolutePath(), imagePath);
	                
//	                Log.i(TAG, "file.exists()不文件存在，网上下载:" + drawable.toString());  
	            } catch (IOException e) {  
	                Log.e(TAG, e.toString() + "图片下载及保存时出现异常！");  
	            }
	        }else  
	        {  
	            drawable = Drawable.createFromPath(file.toString());  
	            Log.i(Constants.TAG, "file.exists()文件存在，本地获取");  
	        } 
	        return drawable ;
		}*/
	  
		
		// 网络图片先下载到本地cache目录保存，以imagUrl的图片文件名保存。如果有同名文件在cache目录就从本地加载
		private Drawable loadImageFromUrl(String imagePath, String imageUrl) {
			Drawable drawable = null;  
			
	        if(imagePath == null && imageUrl == null )  
	            return null;  
	  
	        String pathTmp = imagePath.substring(0, imagePath.lastIndexOf("/"));
	        String fileName = imagePath.substring(imagePath.lastIndexOf("/") + 1);
	        File directory = new File(pathTmp);
	        
	        if (!directory.exists()) {
	        	directory.mkdirs();
			}
	        
	          
	         

	        File fileTmp = new File(Constants.SDCARD_PATH + Constants.PATH_TEMP + fileName);//临时文件 
	        File directoryTmp = new File(Constants.SDCARD_PATH + Constants.PATH_TEMP);
	        
//		        if (fileTmp.exists()) {
//					if (condition) {
//						
//					}
//				}
	        if (!directoryTmp.exists()) {
	        	directoryTmp.mkdirs();
			}
	        
//        	FileOutputStream fos;
	        BufferedOutputStream fos;
            BufferedInputStream is;  
            try {  
                
//            	byte[] b = readByte(imageUrl);
//            	FileIOUtil.saveImage(b, imagePath);
//            	Bitmap bitmap = getPicFormByte(b);    
//            	drawable = new BitmapDrawable(bitmap);   
//                fos=new   FileOutputStream( fileTmp );
            	fos = new BufferedOutputStream(new FileOutputStream(fileTmp));
                is = new BufferedInputStream(new URL(imageUrl).openStream()) ;  
                int   data = is.read();   
                while(data!=-1){
                        fos.write(data);
                        data=is.read();
                }   
                fos.close();  
                is.close(); 
                Log.e("InfoIndexActivity", imageUrl);
                
                BitmapFactory.Options opts = new BitmapFactory.Options();
				opts.inPreferredConfig = Bitmap.Config.RGB_565;
				opts.inPurgeable = true;
				opts.inInputShareable = true;
				
//	              drawable = Drawable.createFromStream(  
//	                      new URL(imageUrl).openStream(), file.toString() ); // (InputStream) new URL(imageUrl).getContent();  
//                drawable = Drawable.createFromPath(fileTmp.toString());  
				drawable = new BitmapDrawable(BitmapFactory.decodeFile(fileTmp.toString(), opts));
//                FileIOUtil.moveFile(fileTmp.getAbsolutePath(), imagePath);
                fileTmp.delete();
	                
//	                Log.i(TAG, "file.exists()不文件存在，网上下载:" + drawable.toString());  
            } catch (IOException e) {  
                Log.e(TAG, e.toString() + "图片下载及保存时出现异常！");  
                urlCache.remove(imageUrl);
            }
	        
	        return drawable ;
		}
		
		// 网络图片先下载到本地cache目录保存，以imagUrl的图片文件名保存。如果有同名文件在cache目录就从本地加载
		public static Drawable loadImageFromLocal(String imagePath) {
			Drawable drawable = null;  
			try {
				File file = new File(imagePath);
				
				
				System.out.println(file);
				if (file.exists()) {
					
//					 FileInputStream fin = new FileInputStream(file);
//					  
//					 byte[] buf = new byte[fin.available()];
//					 fin.read(buf);
//					 Bitmap bm = BitmapFactory.decodeStream(fin);
					   
//					Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
//				   
//					drawable = new BitmapDrawable(bm); 
					
					drawable = Drawable.createFromPath(file.getAbsolutePath());
		            file = null;
		            Log.i(Constants.TAG, "file.exists()文件存在，本地获取");
				}
				
			} catch (Exception e) {
				// TODO: handle exception
				Log.e(Constants.TAG, e.getMessage());
			} 
	      
	        return drawable ;
		}
		
	    public interface ImageCallback{
	    	public void imageLoaded(String savePath,Drawable imageDrawable, List<LoadingView> livList);
	    }

}
